package net.zjitc.servlet.cookies;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CookAServlet",urlPatterns = "/cookAServlet")
public class CookAServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doGet(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //第一次访问时，设置name=zhaojingjing的cookie，
            //第二次访问时，获取并输出此cookies信息
        /**
         * 首先需要获得到cook才可以判断是否有此cookie，有直接获取，没有则进行添加设置
         */
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //获取：头部，request
        Cookie[] cookies = request.getCookies();
        boolean flag = true;
        //处理

        //设置cookie的有效期为1小时
        if (cookies==null || cookies.length == 0){
            Cookie cookie = new Cookie("name", "zhaojingjing");
            cookie.setMaxAge(60*60);
            //添加响应头里
            response.addCookie(cookie);
            writer.write("请求结束，第一次访问");
        }else {
            //存储cookie，就要从这些cookie里面找是否存在name的cook,如果不存在，设置进去
            for (Cookie c: cookies ) {
                if (c.getName().equals("name")){
                    flag = false;
                    writer.write("不是第一次访问");
                }
            }
            //遍历结束，都 没有找到name的cookies，也是第一次访问
            if (flag){
                Cookie cookie = new Cookie("name", "zhaojingjing");
                cookie.setMaxAge(60*60);
                //添加响应头里
                response.addCookie(cookie);
                writer.write("请求结束，第一次访问");
            }
        }

    }
}
/**浏览器调试方式：
  1、F12查看网络
 2、 查看设置里的cookie信息
 */